package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Collect;
import cn.wolfcode.trip.base.mapper.CollectMapper;
import cn.wolfcode.trip.base.query.CollectQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.ICollectService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.jsqlparser.statement.select.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CollectControllerImpl implements ICollectService {
    @Autowired
    private CollectMapper collectMapper;



    //获取当前单条收藏信息 并修改浏览量
    @Override
    public Map get(Collect collect) {
        //查询当前文章的信息
        Map map = collectMapper.selectOne(collect);
        if(collect.getUser()!=null){
            Collect state = collectMapper.selectByPrimaryKey(collect);
            if(state==null){
                map.put("isCollect",false);
            }else {
                map.put("isCollect",true);
            }
        }
        return map;
    }

    //增加一条收藏信息
    @Override
    public void save(Collect collect) {
        //查询当前文章的收藏量
        Map map = collectMapper.selectOne(collect);
        Long collects = (Long) map.get("collects");
        Long coll;

        //先查询当前收藏信息有没有被收藏
        Collect state = collectMapper.selectByPrimaryKey(collect);
        //如果有收藏 则改变它的值 为没有收藏
        if(state!=null){
            coll=collects-1;
            collect.setCollect(coll);
            collectMapper.updateCollectState(collect);
            throw new RuntimeException("取消点赞");
        }


        //把状态改为已收藏
        collect.setCollectState(1);
        //设置浏览量
        Long views = (Long) map.get("views");
        collect.setView(views);
        //设置收藏量
        coll=collects+1;
        collect.setCollect(coll);
        //更新所有的收藏量
        collectMapper.updateCollect(collect);


        //设置收藏时间
        collect.setCollectTime(new Date());
        collectMapper.insert(collect);
    }

    //查看浏览量
    @Override
    public void updataViews(Collect collect) {
        Map map = collectMapper.selectOne(collect);
        Long view = (Long) map.get("views");
        Long views=view+1;
        collect.setView(views);
        collectMapper.updataViews(collect);
    }


    //查询收藏的文章
    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"c.collectTime desc");
        List<Collect> list = collectMapper.selectAll(qo);
        return new PageInfo(list);
    }
}
